'use strict'

const http = require('http');

const server = http.createServer();

//HTTP中的请求类型 GET POST PUT DELETE OPTIONS PATCH HEAD TRACE
//请求时必须携带数据 POST PUT PATCH DELETE(可以携带也可以不携带)
let routeMap = {
    GET:{
        '/':(req,res) => {
            res.setHeader('content-type','text/html;charset="utf-8"');
            res.end("这是首页");
        },
        '/login':(req,res) => {
            res.end("This is login!");
        },
        '/update':(req,res) => {
            res.end("This is update!");
        }
    },
    POST:{
        '/login':(req,res) => {
            res.end(req.bodydata);
        }
    },
    PUT:{
        '/update':(req,res) => {
            res.end(req.bodydata);
        }
    }
}

server.on("request",(req,res) => {
    let urlarr = req.url.split('?');
    let pathname = urlarr[0];
    
    if(routeMap[req.method] === undefined || routeMap[req.method][pathname] === undefined) {
        res.statusCode = 404;
        res.setHeader('content-type','text/html;charset="utf-8"');
        res.end("页面不存在！");
        return ;
    }

    if(['P','D'].indexOf(req.method[0]) >= 0) {
        let bodydata = "";
        req.on("data",chunk => {
            bodydata += chunk.toString('utf8');
        })
        req.on("end",() => {
            req.bodydata = bodydata;
            routeMap[req.method][pathname](req,res);
        })
    } else {
        routeMap[req.method][pathname](req,res);
    }
});

server.listen(8080,() => {
    console.log("Now listening 8080!");
});